package com.htjc.integral.account.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * SOA请求客户端
 * @author sunjinpeng
 *
 */
public class SoaClient {
	private final static Log log = LogFactory.getLog(SoaClient.class);
	//超时时间(毫秒)
	public static final int TIMEOUT=1000*60*6;


	/***
	 * SOA请求
	 * @param wsdl 请求地址
	 * @param envelope 请求体
	 * @param params 参数
	 * @param replaceChar 替换字符
	 * @param authorization 授权
	 * @param charest UTF-8
	 * @param indexStr 要截取的字符串
	 * @return
	 */
	public static Map<String,String> requestSoa(String wsdl,String envelope,String params,String replaceChar,String authorization,String charest,String indexStr){

		//请求体
		envelope = envelope.replace(replaceChar, params);
		log.info("soa请求体内容："+envelope);
		Map<String,String> map = new HashMap<String, String>();
		map.put("fromxml", envelope);
		StringBuffer result = new StringBuffer("");
		HttpURLConnection conn = null;
		OutputStream os = null;
		InputStream is = null;
		try {
			//服务的地址
			URL wsUrl = new URL(wsdl);
			conn = (HttpURLConnection) wsUrl.openConnection();
			conn.setConnectTimeout(TIMEOUT);
			conn.setReadTimeout(TIMEOUT);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Length", String.valueOf(envelope.getBytes().length));
			conn.setRequestProperty("Content-Type", "text/xml;charset="+charest);
			conn.setRequestProperty("SOAPAction", "null");
			if(authorization!=null && !authorization.isEmpty()) {
				conn.addRequestProperty("Authorization", authorization);
			}
			try {
				os = conn.getOutputStream();
				//发送请求
				os.write(envelope.getBytes());
			} catch (Exception e) {
				map.put("success", "false");
				map.put("httpcode", "");
				map.put("result", result.toString());
				map.put("errormsg", e.getMessage());
				e.printStackTrace();
			}
			
			String resultStr = "";
			int responseCode = conn.getResponseCode();
			log.info("[HTTP_CODE]:"+responseCode);
			map.put("httpcode", responseCode+"");
			//请求不成功
			if(!"OK".equals(conn.getResponseMessage().toUpperCase())) {
				map.put("success", "false");
				result.append("error");
			//请求成功
			}else{
				map.put("success", "true");
				
				is = conn.getInputStream();
				byte[] byt = new byte[1024];
				int len = 0;
				while((len = is.read(byt)) != -1){
					String redStr = new String(byt,0,len,charest);
					result.append(redStr);
				}
				
				//截取内容
				try {
					resultStr = SoaClient.subStringForContent(result.toString(), indexStr);
					if(StringUtils.isNotBlank(resultStr)){
						resultStr = StringEscapeUtils.unescapeXml(resultStr);
					}
					log.info("soa-toxml："+result.toString());//打印的是国家电网网上商城个人商城的首页页面
					log.info("===================打印soa-toxml结束===============");
					map.put("toxml", result.toString());
					map.put("result", resultStr);
					map.put("errormsg", "");
				} catch (Exception e) {
					map.put("toxml", result.toString());
					map.put("success", "false");
					map.put("result", result.toString());
					map.put("errormsg", e.getMessage());
					e.printStackTrace();
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(null!=is)
					is.close();
				if(null!=os)
					os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			conn.disconnect();
		}
		return map;
	}
	
	public static String subStringForContent(String str,String indexStr)throws Exception{
//		log.info("********【请求WebService响应报文】************:"+str);
		log.info("********【截取响应报文体的关键字】****************:"+indexStr);
		if(StringUtils.isNotBlank(str)){
	        if(str.indexOf("&lt;")>=0){
	        	str = str.replaceAll("&lt;", "<");
	        }
	        if(str.indexOf("&gt;")>=0){
	        	str = str.replaceAll("&gt;", ">");
	        }
	        if(str.indexOf("\\")>=0){
	        	str = str.replaceAll("\\\\", "");
	        }
			String prefixStr = "<"+indexStr+">";
			String suffixStr = "</"+indexStr+">";
			if(str.indexOf(prefixStr) != -1)
				str = str.substring(str.indexOf(prefixStr)+prefixStr.length(), str.indexOf(suffixStr));
			else
				str ="";
		}
		
		return str;
	}
	
	

	
	public static String subStringForContentNew(String str,String indexStr)throws Exception{
//		log.info("********【请求WebService响应报文】************:"+str);
		log.info("********【截取响应报文体的关键字】****************:"+indexStr);
		if(StringUtils.isNotBlank(str)){
	        if(str.indexOf("&lt;")>=0){
	        	str = str.replaceAll("&lt;", "<");
	        }
	        if(str.indexOf("&gt;")>=0){
	        	str = str.replaceAll("&gt;", ">");
	        }
	        if(str.indexOf("\\")>=0){
	        	str = str.replaceAll("\\\\", "");
	        }
			String prefixStr = "<"+indexStr+">";
			String suffixStr = "</"+indexStr+">";
			if(str.indexOf(prefixStr) != -1){
				if(!"root".equals(indexStr)){
					
					str = str.substring(str.indexOf(prefixStr)+prefixStr.length(), str.indexOf(suffixStr));
				}else{
					str = str.substring(str.indexOf(prefixStr), str.indexOf(suffixStr)+suffixStr.length());
				}
			}else{
				
				str ="";
			}
		}
		
		return str;
	}
	
	

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		SoaClient client = new SoaClient();
		System.out.println(XmlConverUtil.zhejiangStrFormat("<C N=\"rtnMsg\"></C><C N=\"id\">697D1517C860A1D8</C><C N=\"orgNo\">33101</C><C N=\"rtnCode\">1</C>"));
		String reScore = "4324324";
		reScore=reScore.indexOf(".")>-1?reScore.substring(0,reScore.indexOf(".")):reScore;
		System.out.println(reScore);
		
		System.out.println((int)Double.parseDouble("1294"));
		String userName="<234567890><srvC54353ode>0223003</srvCode><channelCode>ESGCC</channelCode><acctId></acctId><userName></userName><orgNo></orgNo><ORDER><srvCode>0223003</srvCode><channelCode>ESGCC</channelCode><acctId></acctId><userName></userName><orgNo></orgNo>";
		userName=userName.length()>10?userName.substring(0,10):userName;
		System.out.println(userName);
		/*Map res = client.requestSoa(   
				"http://sip.esgcc.com.cn/dxp/soa/integral/test/fujian/web/services/EsgccMallServer",
				"<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://server.webservice.core.epm\">"
   +"<soapenv:Header>"
     +"<ns1:username xmlns:ns1=\"Authorization\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">dj</ns1:username>"
    	 +" <ns2:password  xmlns:ns2=\"Authorization\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">1</ns2:password>"
    		 +" </soapenv:Header>"
   +"<soapenv:Body>"
  +" <ser:invokeCimsbInterface soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
	  +"       <xmlStr xsi:type=\"xsd:string\"><![CDATA[<ORDER><servicecode>0223003</servicecode><source>esgcc</source><target>350000</target><data><consNo>0380303347</consNo><orgNo>350000</orgNo></data></ORDER>]]></xmlStr>"
	  +"   </ser:invokeCimsbInterface>"
  +" </soapenv:Body>"
+"</soapenv:Envelope>", 
				"","?","","UTF-8","data");
		System.out.println("花费时间==111" +(System.currentTimeMillis() - start));
		System.out.println("---" +res);
		String resStr=String.valueOf(res.get("result"));*/
		Map res = client.requestSoa("http://sip.esgcc.com.cn/dxp/soa/integral/test/zhejiangnew/qdxt/pf_webservice/spptws/lsspureWs/service",   
				"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.ws.sp.sppt.lsspure\">"
				+"<soapenv:Header>"
				+"<ns1:username xmlns:ns1=\"Authorization\">sysadmin</ns1:username>"
						+"<ns1:password xmlns:ns1=\"Authorization\">1</ns1:password>"
								+"</soapenv:Header>"
								+"<soapenv:Body>"
								+"<ser:invoke>"
								+"<ser:path>cimsb/cimsb/manage/service/consImBalService</ser:path>"
								+"<ser:methodName>getImBal</ser:methodName>"
								+"<ser:dataXmlStr><![CDATA["
										+"<DBSET>"
										+"<R>"
										+"<C N=\"srvCode\">0223003</C>"
												+"<C N=\"channelCode\">ESGCC</C>"
														+"<C N=\"acctId\">ESGCC5zhongheng</C>"
																+"<C N=\"userName\">zhongheng</C>"
																		+" <C N=\"consNo\">3207116030</C>"
																				+"<C N=\"orgNo\">330000</C>"
																						+"</R>"
																						+"</DBSET>]]>"
																						+"</ser:dataXmlStr>"
																						+"</ser:invoke>"
																						+"</soapenv:Body>"
																						+"</soapenv:Envelope>", 
				"","?","","UTF-8","R");
		System.out.println("花费时间==111" +(System.currentTimeMillis() - start));
		System.out.println("---" +res);
		String resStr=String.valueOf(res.get("result"));
		System.out.println("---result:" +resStr);
		resStr=XmlConverUtil.zhejiangStrFormat(resStr);
		Map<String,Object> map = new HashMap<String,Object>();
		//map=XmlConverUtil.ResultXmltoMap(String.valueOf(res.get("result")));
		//List<Map<String,Object>> list=XmlConverUtil.ResultXmltoListMap(String.valueOf(res.get("result")));
		map=XmlConverUtil.ResultXmltoMap(resStr);
		System.out.println("---" +String.valueOf(map));
		
	}
	
}
